package com.pig4cloud.pig.module.service.mer.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.TransactionalException;
import com.pig4cloud.pig.common.core.util.OrderUtil;
import com.pig4cloud.pig.common.core.wx.WxAppPay;
import com.pig4cloud.pig.module.api.entity.excel.MerEggSettlementExcel;
import com.pig4cloud.pig.module.api.entity.farm.FarmFeedRecord;
import com.pig4cloud.pig.module.api.entity.mer.MerEggSettlement;
import com.pig4cloud.pig.module.api.entity.wx.WxPayTransaction;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.mapper.mer.MerEggSettlementMapper;
import com.pig4cloud.pig.module.service.farm.IFarmFeedRecordService;
import com.pig4cloud.pig.module.service.mer.IMerEggSettlementService;
import com.pig4cloud.pig.module.service.wx.IWxPayTransactionService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 结算金额Service业务层处理
 *
 * @author ruoyi
 * @date 2022-05-20
 */
@Service
public class MerEggSettlementServiceImpl extends ServiceImpl<MerEggSettlementMapper, MerEggSettlement> implements IMerEggSettlementService {

    @Resource
    private MerEggSettlementMapper  eggSettlementMapper;
    @Resource
    private IWxTemplateService wxTemplateService;
    @Resource
    private IWxUserService wxUserService;
	@Resource
	private IFarmFeedRecordService farmFeedRecordService;
	@Resource
	private IWxPayTransactionService payTransactionService;

    @Value("${web.appid}")
    private String appid;
    @Value("${web.appidMp}")
    private String appidMp;
    @Value("${web.secret}")
    private String secret;
    @Value("${web.mch_id}")
    private String mch_id;
    @Value("${web.api_key}")
    private String api_key;
    @Value("${web.keyPath}")
    private String keyPath;//微信支付的回调地址

    @Override
    @Transactional
    public Map<String, Object> checkRecord(MerEggSettlement eggSettlement) {
        Map<String,Object> map = new HashMap<>();
        int ret = 0;
        try{
			int status = 0;
        	if(eggSettlement.getState() == 1){
				eggSettlement.setState(2);
				String tradeNo = OrderUtil.getPayNo();
				eggSettlement.setTradeNo(tradeNo);
				map.put("result_code","FAIL");
				map.put("err_code_des","请求失败");
				WxAppPay wxAppPay = new WxAppPay("", secret, appid, mch_id,api_key);
				Map<String, String> retRequest = wxAppPay.weixinChangePay(eggSettlement.getTradeNo(),eggSettlement.getPayMoney(),eggSettlement.getWxOpenId(),keyPath,"领蛋结算款");
				if(retRequest.containsKey("return_code")){
					String return_code = retRequest.get("return_code");
					String result_code = retRequest.get("result_code");
					String err_code_des = retRequest.containsKey("err_code_des") ? retRequest.get("err_code_des") : "";
					map.put("result_code",result_code);
					map.put("err_code_des",err_code_des);
					eggSettlement.setResultCode(result_code);
					if(result_code.equals("SUCCESS")){
						eggSettlement.setPayState(1);//支付成功
						eggSettlement.setPayTime(new Date());
						map.put("err_code_des","提现成功");
						//结算状态 0  - 待结算  1 - 已结算  2 - 取消结算 3 - 已打款  4 - 打款失败
						eggSettlement.setState(3);


						WxUser wxUser = wxUserService.findById(eggSettlement.getUserId());
						// 添加 微信支付的 动账记录
						WxPayTransaction transaction = new WxPayTransaction();
						transaction.setTransactionNo(eggSettlement.getTradeNo());
						transaction.setPayType(0);// 0 -微信支付
						transaction.setTransactionId(eggSettlement.getTradeNo());
						transaction.setUserId(wxUser.getId());
						transaction.setFeeType("egg_settle");
						transaction.setTotalMoney(eggSettlement.getPayMoney());
						if(StrUtil.isNotEmpty(wxUser.getNickName())){
							transaction.setNickName(EmojiParser.parseToAliases(wxUser.getNickName()));
						}
						transaction.setMerId(eggSettlement.getMerId());
						transaction.setMerName(eggSettlement.getMerName());
						transaction.setCreateTime(new Date());
						transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
						transaction.setRemark("领蛋结算款");
						payTransactionService.save(transaction);


						status = 1;
					}else{
						eggSettlement.setState(4);
						eggSettlement.setPayState(2);//支付失败
						eggSettlement.setErrCodeDes(err_code_des);
					}
					String pay_str = retRequest.get("pay_str");
					String reback_str = retRequest.get("reback_str");
					eggSettlement.setPayStr(pay_str);
					eggSettlement.setRebackStr(reback_str);
				}
			}

            ret = eggSettlementMapper.updateById(eggSettlement);
            if(ret <= 0){
                throw new TransactionalException("cashRecordMapper updateById error");
            }


			farmFeedRecordService.update(new LambdaUpdateWrapper<FarmFeedRecord>()
				.set(FarmFeedRecord::getIsSettle,2)
				.set(FarmFeedRecord::getSettleOverTime, new Date())
				.eq(FarmFeedRecord::getSettleRecordId,eggSettlement.getId()));

            if(status == 1){
                WxUser wxUser = wxUserService.findById(eggSettlement.getUserId());
                wxTemplateService.sendWxMsgEggSettle(wxUser,eggSettlement,eggSettlement.getPayMoney().doubleValue());
            }
            map.put("ret",ret);
            return map;
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("splitAccountRecordMapper insert error");
        }
    }

	@Override
	public Page<MerEggSettlement> selectSettlementByMerId(Page<MerEggSettlement> page, Map<String, Object> map) {
		return eggSettlementMapper.selectSettlementByMerId(page,map);
	}

	@Override
	public List<MerEggSettlementExcel> selectSettlementTongjiByMerId(Map<String, Object> map) {
		return eggSettlementMapper.selectSettlementTongjiByMerId(map);
	}
}
